﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="ExpectedDate_FormItem" prop="ExpectedDate">
							<template #label>
								<WtmLabelTooltip label="到岗时间" tooltip="期望人员到岗的时间" />
							</template>
							<el-date-picker type="daterange" v-model="searchData.ExpectedDate" clearable></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="JobRequirement_FormItem" prop="JobRequirement">
							<template #label>
								<WtmLabelTooltip label="岗位要求" tooltip="岗位的具体要求" />
							</template>
							<el-input v-model="searchData.JobRequirement" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="EducationRequirement_FormItem" prop="EducationRequirement">
							<template #label>
								<WtmLabelTooltip label="学历要求" tooltip="最低学历要求" />
							</template>
							<el-select v-model="searchData.EducationRequirement" clearable>
								<el-option v-for="item in EDUCATION_OPTIONS" :key="item" :value="item" :label="item"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MajorRequirement_FormItem" prop="MajorRequirement">
								<template #label>
									<WtmLabelTooltip label="专业要求" tooltip="所需专业方向" />
								</template>
								<el-input v-model="searchData.MajorRequirement" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="GenderRequirement_FormItem" prop="GenderRequirement">
								<template #label>
									<WtmLabelTooltip label="性别要求" tooltip="岗位对性别的要求" />
								</template>
								<el-select v-model="searchData.GenderRequirement" clearable>
									<el-option v-for="item in GENDER_OPTIONS" :key="item" :value="item" :label="item"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="AgeRequirement_FormItem" prop="AgeRequirement">
								<template #label>
									<WtmLabelTooltip label="年龄要求" tooltip="岗位对年龄的要求" />
								</template>
								<el-input v-model="searchData.AgeRequirement" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="HrStaffNeedId_FormItem" prop="HrStaffNeedId">
								<template #label>
									<WtmLabelTooltip label="用人申请单号" tooltip="关联的用人申请单" />
								</template>
								<el-select v-model="searchData.HrStaffNeedId" :data="stateData.AllSysHrStaffNeedRequestBills" clearable>
									<el-option
										v-for="item in stateData.AllSysHrStaffNeedRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrStaffNeedRequestBillEntry/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffNeedRequestBillEntry/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffNeedRequestBillEntry/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffNeedRequestBillEntry/SysHrStaffNeedRequestBillEntryExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrStaffNeedRequestBillEntry/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrStaffNeedRequestBillEntry/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrStaffNeedRequestBillEntry/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="用人需求明细;true;HengTong.Areas.Hr.Controllers;SysHrStaffNeedRequestBillEntry">
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed, type ComponentInternalInstance } from 'vue';
import { SysHrStaffNeedRequestBillEntryApi as api } from '/@/views/hr/syshrstaffneedrequestbillentry/api';
import { ISysHrStaffNeedRequestBillEntryView, ISysHrStaffNeedRequestBillEntryQuery } from '/@/views/hr/syshrstaffneedrequestbillentry/api/interface';
import other from '/@/utils/other';

// 懒加载子组件
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

// 常量定义
const EDUCATION_OPTIONS = ['小学', '初中', '高中', '中专', '大专', '本科', '研究生', '硕士', '博士', '博士后', '博士研究生', '其他'] as const;

const GENDER_OPTIONS = ['男', '女', '其他'] as const;

const API_ENDPOINTS = {
	BILLS: '/api/SysHrStaffNeedRequestBillEntry/GetSysHrStaffNeedRequestBills',
} as const;

const TABLE_HEADERS = [
	// 核心信息（最高优先级）
	{ title: '用人申请单号', key: 'HrStaffNeedName', type: 'text', isCheck: true },
	{ title: '公司', key: 'OrgName', type: 'text', isCheck: true },
	{ title: '所属部门', key: 'GroupName', type: 'text', isCheck: true },
	{ title: '工作岗位', key: 'JobPositionName', type: 'text', isCheck: true },
	{ title: '招聘人数', key: 'HireNumber', type: 'text', isCheck: true },

	// 时间要求（高优先级）
	{ title: '到岗时间', key: 'ExpectedDate', type: 'text', isCheck: true },

	// 需求描述（中高优先级）
	{ title: '申请原因', key: 'ApplyReason', type: 'text', isCheck: true },
	{ title: '岗位要求', key: 'JobRequirement', type: 'text', isCheck: true },

	// 任职要求（中优先级）
	{ title: '学历要求', key: 'EducationRequirement', type: 'text', isCheck: true },
	{ title: '专业要求', key: 'MajorRequirement', type: 'text', isCheck: true },
	{ title: '性别要求', key: 'GenderRequirement', type: 'text', isCheck: true },
	{ title: '年龄要求', key: 'AgeRequirement', type: 'text', isCheck: true },

	// 补充信息（低优先级）
	{ title: '其他要求', key: 'OtherRequirement', type: 'text', isCheck: true },
] as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrStaffNeedRequestBillEntryQuery;
		/** 主表ID */
		entityId?: string | null;
		/** 部门ID */
		groupId?: string | null;
		/** 公司ID */
		orgId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
		groupId: null,
		orgId: null,
	}
);

const stateData = reactive({
	AllSysHrStaffNeedRequestBills: [] as any[],
});

const searchData = ref<ISysHrStaffNeedRequestBillEntryQuery>({});
const tableRef = ref();

// 初始化表格数据
const tableData = ref({
	data: [],
	header: TABLE_HEADERS,
	config: {
		total: 0,
		loading: true,
		isSerialNo: true,
		isSelection: true,
		isOperate: props.isDisabled,
	},
});

// 计算属性 - 判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		handleError(error);
	}
};

// 对话框操作
const OnCreateClick = () => {
	const data = props.entityId ? { entityId: props.entityId, groupId: props.groupId, orgId: props.orgId } : null;
	other.openDialog(ci.proxy?.$t('message._system.common.vm.add') || '新增', CreateDialog, data, getTableData, '50%');
};

const OnEditRowClick = (row: ISysHrStaffNeedRequestBillEntryView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.edit') || '编辑', EditDialog, row, getTableData, '50%');
};

const OnDetailsRowClick = (row: ISysHrStaffNeedRequestBillEntryView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.detail') || '详情', DetailsDialog, row, getTableData, '50%');
};

const OnImportClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.import') || '导入', ImportDialog, null, getTableData);
};

// 删除操作
const onDelete = async (row: ISysHrStaffNeedRequestBillEntryView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		await api().delete(ids);
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrStaffNeedRequestBillEntryView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy?.$t('message._system.common.vm.error') || '操作失败');
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要删除的数据');
	}
};

// 导出操作
const onExport = () => {
	const selected = tableRef.value?.getSelectedRows();
	if (selected && selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		const [bills] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.BILLS, [], false)]);

		// 处理选择列表结果，即使部分失败也继续
		if (bills.status === 'fulfilled') stateData.AllSysHrStaffNeedRequestBills = bills.value;
	} catch (error) {
		// 静默处理错误
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	// 如果有entityId，自动设置搜索条件
	if (props.entityId) {
		searchData.value.HrStaffNeedId = props.entityId;
	}

	try {
		// 并行加载选择列表数据和表格数据
		await Promise.all([loadSelectListData(), getTableData()]);
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
});
</script>
